﻿using Microsoft.AspNetCore.Mvc;
using System.Net;
using yunbo.Model.RMM;
using yunbo.Repositorys.RMMRepositorys;

namespace yunbo.Controllers.RMMControllers
{
    [ApiController]
    [Route("api/upload")]
    public class UploadController : ControllerBase
    {
        private readonly AttachmentRepository _attachmentRepository;

        public UploadController(AttachmentRepository attachmentRepository)
        {
            _attachmentRepository = attachmentRepository;
        }

        [HttpPost("upload")]
        public async Task<IActionResult> UploadFile(IFormFile file, [FromForm] string yclcg_code, [FromForm] string attachments_lx, [FromForm] int create_by)
        {
            if (file == null || file.Length == 0)
                return BadRequest("No file uploaded.");

            var uploadsFolderPath = Path.Combine(Directory.GetCurrentDirectory(), "Uploads");
            if (!Directory.Exists(uploadsFolderPath))
                Directory.CreateDirectory(uploadsFolderPath);
            var uniqueFileName = Guid.NewGuid().ToString() + "_" + file.FileName;
            var filePath = Path.Combine(uploadsFolderPath, uniqueFileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            var attachment = new Attachment
            {
                yclcg_code = yclcg_code,
                attachments_lx = attachments_lx,
                attachments_url = filePath,
                create_by = create_by,
                create_time = DateTime.UtcNow
            };

            try
            {
                var attachmentId = await _attachmentRepository.SaveAttachmentToDb(attachment);
                return Ok(new { AttachmentId = attachmentId });
            }
            catch (Exception ex)
            {
                // 记录日志
                Console.WriteLine($"Error saving attachment to database: {ex.Message}");
                return StatusCode(500, "Internal server error");
            }
        }
    }
}
